package com.iotimc.attendancesystem.manage.fragment;

import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.media.SoundPool;
import android.net.Uri;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.SeekBar;

import com.iotimc.attendancesystem.App;
import com.iotimc.attendancesystem.R;
import com.iotimc.attendancesystem.base.BaseFragment;
import com.iotimc.attendancesystem.dao.BasicSettingEntityDao;
import com.iotimc.attendancesystem.dao.GreenDaoManager;
import com.iotimc.attendancesystem.entity.BasicSettingEntity;
import com.iotimc.attendancesystem.io.CardCommonPresenter;
import com.iotimc.attendancesystem.util.TtsUtil;
import com.iotimc.attendancesystem.util.WindowUtils;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author david
 * @date 2017/11/28
 * <p>
 * ATTENDANCES 自动门
 */

public class SystemSettingFragment extends BaseFragment {
    @BindView(R.id.et_setting_company)
    EditText etSettingCompany;
    @BindView(R.id.et_setting_time)
    EditText etSettingTime;
    @BindView(R.id.et_setting_ip)
    EditText etSettingIp;
    @BindView(R.id.et_setting_similarity)
    EditText etSettingSimilarity;
    @BindView(R.id.et_setting_delay)
    EditText etSettingDelay;
    @BindView(R.id.bt_setting_commit)
    Button btSettingCommit;
    @BindView(R.id.et_setting_admin)
    EditText etSettingAdmin;
    @BindView(R.id.et_setting_type_door_auto)
    CheckBox mEtSettingTypeDoorAuto;

    @BindView(R.id.cb_setting_button_bell)
    CheckBox mcbBell;
    @BindView(R.id.cb_setting_button_door)
    CheckBox mcbDoor;


    @BindView(R.id.et_setting_type_door_manual)
    CheckBox mEtSettingTypeDoorManual;
    @BindView(R.id.ll_manage_setting_door_delay)
    LinearLayout mEtSettingDelay;
    @BindView(R.id.seek_bar)
    SeekBar seekBar;

    private BasicSettingEntityDao basicSettingEntityDao;
    private BasicSettingEntity load;
    AudioManager audioManager;
    @Override
    protected void initView(View view) {
        super.initView(view);
        audioManager =(AudioManager)getActivity().getSystemService(Context.AUDIO_SERVICE);
        seekBar.setProgress(audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,progress, AudioManager.FLAG_PLAY_SOUND);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                CardCommonPresenter.getInstance().getSoundPool()
                        .play(1,1, 1, 0, 0, 1);
            }
        });
    }

    @Override
    protected int getResId() {
        return R.layout.fragment_person_setting;
    }

    @OnClick(R.id.bt_setting_net)
    void netSetting() {
        Intent intent = new Intent(Settings.ACTION_AIRPLANE_MODE_SETTINGS);
        startActivity(intent);

        WindowUtils.showPopupWindow(App.getAppContext());
    }

    @OnClick({R.id.et_setting_type_door_auto})
    void boxAuto() {
        mEtSettingTypeDoorAuto.setChecked(true);
        mEtSettingTypeDoorManual.setChecked(false);
        mEtSettingDelay.setVisibility(View.VISIBLE);
    }

    @OnClick({R.id.et_setting_type_door_manual})
    void boxManual() {
        mEtSettingTypeDoorAuto.setChecked(false);
        mEtSettingTypeDoorManual.setChecked(true);
        mEtSettingDelay.setVisibility(View.INVISIBLE);
    }


    @OnClick({R.id.cb_setting_button_bell})
    void boxBell() {
        mcbBell.setChecked(true);
        mcbDoor.setChecked(false);
    }

    @OnClick({R.id.cb_setting_button_door})
    void boxDoor() {
        mcbBell.setChecked(false);
        mcbDoor.setChecked(true);
    }

    @OnClick(R.id.bt_setting_commit)
    void commit() {
        if (basicSettingEntityDao != null && basicSettingEntityDao.count() > 0) {
            String company = String.valueOf(etSettingCompany.getText()).trim();
            String time = String.valueOf(etSettingTime.getText()).trim();
            String ip = String.valueOf(etSettingIp.getText()).trim();
            String similarity = String.valueOf(etSettingSimilarity.getText()).trim();
            String admin = String.valueOf(etSettingAdmin.getText()).trim();
            String sDelay = etSettingDelay.getText().toString();

            boolean autoDoor = mEtSettingTypeDoorAuto.isChecked();
            boolean manualDoor = mEtSettingTypeDoorManual.isChecked();

            if (TextUtils.isEmpty(admin)) {
                etSettingAdmin.setHintTextColor(getActivity().getResources().getColor(R.color.red));
                etSettingAdmin.setText("");
                etSettingAdmin.setHint("管理员密码不能为空");
                TtsUtil.ttsSpeek2("管理员密码不能为空");
                return;
            }

            if (TextUtils.isEmpty(time)) {
                etSettingTime.setHintTextColor(getActivity().getResources().getColor(R.color.red));
                etSettingTime.setText("");
                etSettingTime.setHint("时间不能为空");
                TtsUtil.ttsSpeek2("时间不能为空");
                return;
            }


            if (TextUtils.isEmpty(similarity)) {
                etSettingSimilarity.setHintTextColor(getActivity().getResources().getColor(R.color.red));
                etSettingSimilarity.setText("");
                etSettingSimilarity.setHint("相似度不能为空");
                TtsUtil.ttsSpeek2("相似度不能为空");
                return;
            }

            if (TextUtils.isEmpty(sDelay)) {
                etSettingDelay.setHintTextColor(getActivity().getResources().getColor(R.color.red));
                etSettingDelay.setText("");
                etSettingDelay.setHint("延迟关门时间不能为空");
                TtsUtil.ttsSpeek2("延迟关门时间不能为空");
                return;
            }

            int delay = Integer.valueOf(sDelay);

            boolean contains = similarity.contains(".");
            if (contains) {
                similarity = similarity.substring(0, similarity.indexOf("."));
            }
            Integer intSimilarity = Integer.valueOf(similarity);
            if (intSimilarity > 100) {
                TtsUtil.ttsSpeek2("相似度不能大于100");
                etSettingSimilarity.setText("");
                etSettingSimilarity.setHintTextColor(getActivity().getResources().getColor(R.color.red));
                etSettingSimilarity.setHint("相似度不能大于100");
                return;
            } else if (intSimilarity < 60) {
                TtsUtil.ttsSpeek2("相似度不能小于60");
                etSettingSimilarity.setText("");
                etSettingSimilarity.setHintTextColor(getActivity().getResources().getColor(R.color.red));
                etSettingSimilarity.setHint("相似度不能小于60");
                return;
            }

            BasicSettingEntity.DeviceType attendances;
            if (autoDoor) {
                attendances = BasicSettingEntity.DeviceType.AUTO_DOOR;
            } else if (manualDoor) {
                attendances = BasicSettingEntity.DeviceType.MANUAL_DOOR;
                delay = 30;
            } else {
                attendances = BasicSettingEntity.DeviceType.DEFAULT;
                delay = 30;
            }

            boolean buttonBell = mcbBell.isChecked();
            boolean buttonDoor = mcbDoor.isChecked();
            BasicSettingEntity.ButtonType buttonType;
            if (buttonDoor) {
                buttonType = BasicSettingEntity.ButtonType.OPEN_DOOR;
            } else {
                buttonType = BasicSettingEntity.ButtonType.DOOR_BELL;
            }

            time = String.valueOf(Integer.valueOf(time) < 1 ? 1 : time);

            //delay
            delay = delay < 0 ? 30 : delay;

            load.setCompanyName(company);
            load.setTime(Integer.valueOf(time));
            load.setSimilarityScore(Integer.valueOf(similarity));
            load.setPassword(admin);
            load.setDoorIp(ip);
            load.setDeviceType(attendances);
            load.setDelayDoorSecond(delay);
            load.setButtonType(buttonType);
            basicSettingEntityDao.update(load);
            TtsUtil.ttsSpeek2("修改成功");
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (basicSettingEntityDao != null && basicSettingEntityDao.count() > 0) {
                load = basicSettingEntityDao.load(1L);

                String name = load.getCompanyName();
                int time = load.getTime();
                String ip = load.getDoorIp();
                int score = load.getSimilarityScore();
                String password = load.getPassword();
                int second = load.getDelayDoorSecond();

                if (!TextUtils.isEmpty(name)) {
                    etSettingCompany.setText(name);
                } else {
                    etSettingCompany.setText("");
                }

                if (time > -1) {
                    etSettingTime.setText(String.valueOf(time));
                }

                if (!TextUtils.isEmpty(ip)) {
                    etSettingIp.setText(ip);
                } else {
                    etSettingIp.setText("");
                }
                if (score > -1) {
                    etSettingSimilarity.setText(String.valueOf(score));
                }

                etSettingAdmin.setText(password);

                if (second > -1) {
                    etSettingDelay.setText(String.valueOf(second));
                }

                BasicSettingEntity.DeviceType deviceType = load.getDeviceType();
                if (deviceType == BasicSettingEntity.DeviceType.MANUAL_DOOR) {
                    mEtSettingTypeDoorAuto.setChecked(false);
                    mEtSettingTypeDoorManual.setChecked(true);
                    mEtSettingDelay.setVisibility(View.INVISIBLE);
                } else if (deviceType == BasicSettingEntity.DeviceType.AUTO_DOOR) {
                    mEtSettingTypeDoorAuto.setChecked(true);
                    mEtSettingTypeDoorManual.setChecked(false);
                    mEtSettingDelay.setVisibility(View.VISIBLE);
                } else {
                    mEtSettingTypeDoorAuto.setChecked(false);
                    mEtSettingTypeDoorManual.setChecked(false);
                    mEtSettingDelay.setVisibility(View.INVISIBLE);
                }

                BasicSettingEntity.ButtonType buttonType = load.getButtonType();
                if (buttonType == BasicSettingEntity.ButtonType.DOOR_BELL) {
                    mcbBell.setChecked(true);
                    mcbDoor.setChecked(false);
                } else if (buttonType == BasicSettingEntity.ButtonType.OPEN_DOOR) {
                    mcbBell.setChecked(false);
                    mcbDoor.setChecked(true);
                } else {
                    mcbBell.setChecked(false);
                    mcbDoor.setChecked(false);
                }
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();

    }

    private void initData() {
        basicSettingEntityDao = GreenDaoManager.getInstance().getSession().getBasicSettingEntityDao();
        if (basicSettingEntityDao != null && basicSettingEntityDao.count() > 0) {
            load = basicSettingEntityDao.load(1L);

            String name = load.getCompanyName();
            int time = load.getTime();
            String ip = load.getDoorIp();
            int score = load.getSimilarityScore();
            String password = load.getPassword();
            int second = load.getDelayDoorSecond();

            if (!TextUtils.isEmpty(name)) {
                etSettingCompany.setText(name);
            } else {
                etSettingCompany.setText("");
            }

            if (time > -1) {
                etSettingTime.setText(String.valueOf(time));
            }

            if (!TextUtils.isEmpty(ip)) {
                etSettingIp.setText(ip);
            } else {
                etSettingIp.setText("");
            }
            if (score > -1) {
                etSettingSimilarity.setText(String.valueOf(score));
            }

            etSettingAdmin.setText(password);

            if (second > -1) {
                etSettingDelay.setText(String.valueOf(second));
            }

            BasicSettingEntity.DeviceType deviceType = load.getDeviceType();
            if (deviceType == BasicSettingEntity.DeviceType.MANUAL_DOOR) {
                mEtSettingTypeDoorAuto.setChecked(false);
                mEtSettingTypeDoorManual.setChecked(true);
                mEtSettingDelay.setVisibility(View.INVISIBLE);
            } else if (deviceType == BasicSettingEntity.DeviceType.AUTO_DOOR) {
                mEtSettingTypeDoorAuto.setChecked(true);
                mEtSettingTypeDoorManual.setChecked(false);
                mEtSettingDelay.setVisibility(View.VISIBLE);
            } else {
                mEtSettingTypeDoorAuto.setChecked(false);
                mEtSettingTypeDoorManual.setChecked(false);
                mEtSettingDelay.setVisibility(View.INVISIBLE);
            }

            BasicSettingEntity.ButtonType buttonType = load.getButtonType();
            if (buttonType == BasicSettingEntity.ButtonType.DOOR_BELL) {
                mcbBell.setChecked(true);
                mcbDoor.setChecked(false);
            } else if (buttonType == BasicSettingEntity.ButtonType.OPEN_DOOR) {
                mcbBell.setChecked(false);
                mcbDoor.setChecked(true);
            } else {
                mcbBell.setChecked(false);
                mcbDoor.setChecked(false);
            }
        }
    }
}
